package cn.mujiankeji.mbrowser.界面.小窗页.管理

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.数据.数据库.AppDatabase
import cn.mujiankeji.mbrowser.数据.数据库.DBUa
import cn.mujiankeji.mbrowser.界面.框架.小窗视图.小窗状态
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class UA标识管理窗口状态() : 小窗状态(), KoinComponent {
    private val 数据库: AppDatabase by inject()
    
    // UA列表
    private val _ua列表 = MutableStateFlow<List<DBUa>>(emptyList())
    val ua列表: StateFlow<List<DBUa>> = _ua列表
    
    // 编辑状态
    var 正在编辑的UA by mutableStateOf<DBUa?>(null)
    var 显示编辑对话框 by mutableStateOf(false)
    var 显示删除确认对话框 by mutableStateOf(false)
    
    // 临时编辑字段
    var 临时名称 by mutableStateOf("")
    var 临时UA by mutableStateOf("")
    var 临时备注 by mutableStateOf("")
    
    // 加载UA列表
    fun 加载UA列表(scope: CoroutineScope) {
        scope.launch {
            数据库.UA标识().获取所有UA().collect {
                _ua列表.value = it
            }
        }
    }
    
    // 准备添加UA
    fun 准备添加UA() {
        临时名称 = ""
        临时UA = ""
        临时备注 = ""
        正在编辑的UA = null
        显示编辑对话框 = true
    }
    
    // 准备编辑UA
    fun 准备编辑UA(ua: DBUa) {
        临时名称 = ua.名称
        临时UA = ua.UA
        临时备注 = ua.备注
        正在编辑的UA = ua
        显示编辑对话框 = true
    }
    
    // 保存UA
    fun 保存UA(scope: CoroutineScope) {
        scope.launch {
            withContext(Dispatchers.IO) {
                val ua = 正在编辑的UA?.copy(
                    名称 = 临时名称,
                    UA = 临时UA,
                    备注 = 临时备注,
                    更新时间 = System.currentTimeMillis()
                ) ?: DBUa(
                    名称 = 临时名称,
                    UA = 临时UA,
                    备注 = 临时备注,
                    更新时间 = System.currentTimeMillis()
                )
                
                if (正在编辑的UA == null) {
                    数据库.UA标识().添加UA(ua)
                } else {
                    数据库.UA标识().更新UA(ua)
                }
            }
            显示编辑对话框 = false
        }
    }
    
    // 准备删除UA
    fun 准备删除UA(ua: DBUa) {
        正在编辑的UA = ua
        显示删除确认对话框 = true
    }
    
    // 删除UA
    fun 删除UA(scope: CoroutineScope) {
        scope.launch {
            withContext(Dispatchers.IO) {
                正在编辑的UA?.let {
                    数据库.UA标识().删除UA(it)
                }
            }
            显示删除确认对话框 = false
        }
    }
    
    // 设置默认UA
    fun 设置默认UA(ua: DBUa, scope: CoroutineScope) {
        scope.launch {
            withContext(Dispatchers.IO) {
                数据库.UA标识().设置默认UA(ua.id)
            }
        }
    }
    
    // 关闭窗口
    fun 关闭窗口() {
        销毁小窗()
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UA标识管理窗口实现(state: 小窗状态) {
    if (state !is UA标识管理窗口状态) return
    
    val scope = rememberCoroutineScope()
    val ua列表 = state.ua列表.collectAsState(initial = emptyList())
    
    // 加载UA列表
    LaunchedEffect(Unit) {
        state.加载UA列表(scope)
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("UA标识管理") },
                navigationIcon = {
                    IconButton(onClick = { state.关闭窗口() }) {
                        Icon(Icons.Default.Close, contentDescription = "关闭")
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(onClick = { state.准备添加UA() }) {
                Icon(Icons.Default.Add, contentDescription = "添加UA")
            }
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            if (ua列表.value.isEmpty()) {
                // 空状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text("暂无UA标识，点击右下角按钮添加")
                }
            } else {
                // UA列表
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    items(ua列表.value) { ua ->
                        UA项目(
                            ua = ua,
                            onEdit = { state.准备编辑UA(ua) },
                            onDelete = { state.准备删除UA(ua) },
                            onSetDefault = { state.设置默认UA(ua, scope) }
                        )
                        Divider()
                    }
                }
            }
            
            // 编辑对话框
            if (state.显示编辑对话框) {
                UA编辑对话框(
                    名称 = state.临时名称,
                    ua = state.临时UA,
                    备注 = state.临时备注,
                    onNameChange = { state.临时名称 = it },
                    onUaChange = { state.临时UA = it },
                    onRemarkChange = { state.临时备注 = it },
                    onConfirm = { state.保存UA(scope) },
                    onDismiss = { state.显示编辑对话框 = false }
                )
            }
            
            // 删除确认对话框
            if (state.显示删除确认对话框) {
                AlertDialog(
                    onDismissRequest = { state.显示删除确认对话框 = false },
                    title = { Text("确认删除") },
                    text = { Text("确定要删除 ${state.正在编辑的UA?.名称 ?: ""} 吗？") },
                    confirmButton = {
                        TextButton(onClick = { state.删除UA(scope) }) {
                            Text("确定")
                        }
                    },
                    dismissButton = {
                        TextButton(onClick = { state.显示删除确认对话框 = false }) {
                            Text("取消")
                        }
                    }
                )
            }
        }
    }
}

@Composable
fun UA项目(
    ua: DBUa,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
    onSetDefault: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // 标题行
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = ua.名称,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                
                Spacer(modifier = Modifier.weight(1f))
                
                // 默认标记
                if (ua.默认) {
                    Box(
                        modifier = Modifier
                            .background(
                                color = MaterialTheme.colorScheme.primary,
                                shape = MaterialTheme.shapes.small
                            )
                            .padding(horizontal = 8.dp, vertical = 4.dp)
                    ) {
                        Text(
                            text = "默认",
                            color = MaterialTheme.colorScheme.onPrimary,
                            style = MaterialTheme.typography.labelSmall
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // UA内容
            Text(
                text = ua.UA,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            // 备注（如果有）
            if (ua.备注.isNotEmpty()) {
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "备注: ${ua.备注}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 设为默认按钮
                if (!ua.默认) {
                    TextButton(onClick = onSetDefault) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = "设为默认",
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text("设为默认")
                    }
                }
                
                Spacer(modifier = Modifier.weight(1f))
                
                // 编辑按钮
                IconButton(onClick = onEdit) {
                    Icon(
                        Icons.Default.Edit,
                        contentDescription = "编辑",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
                
                // 删除按钮
                IconButton(onClick = onDelete) {
                    Icon(
                        Icons.Default.Delete,
                        contentDescription = "删除",
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }
        }
    }
}

@Composable
fun UA编辑对话框(
    名称: String,
    ua: String,
    备注: String,
    onNameChange: (String) -> Unit,
    onUaChange: (String) -> Unit,
    onRemarkChange: (String) -> Unit,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("编辑UA标识") },
        text = {
            Column {
                OutlinedTextField(
                    value = 名称,
                    onValueChange = onNameChange,
                    label = { Text("名称") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                OutlinedTextField(
                    value = ua,
                    onValueChange = onUaChange,
                    label = { Text("UA字符串") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                OutlinedTextField(
                    value = 备注,
                    onValueChange = onRemarkChange,
                    label = { Text("备注") },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        },
        confirmButton = {
            Button(
                onClick = onConfirm,
                enabled = 名称.isNotBlank() && ua.isNotBlank()
            ) {
                Text("保存")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

